<div class="layui-card">
    <div class="layui-card-header">
        <h2 class="header-title">员工管理</h2>
    </div>

    <div class="layui-card-body">
        <div class="layui-form toolbar">
            查询：<input id="app-edit-search" class="layui-input search-input" type="text" placeholder="输入关键字"/>&emsp;
            <button class="layui-btn layui-btn-normal layui-btn-sm icon-btn" data-method="doQuery">
                <i class="layui-icon">&#xe615;</i>搜索
            </button>
            <button class="layui-btn layui-btn-normal layui-btn-sm icon-btn" data-method="doAdd">添加</button>
        </div>

        <!-- 数据表格 -->
        <table class="layui-table" id="app-table" lay-filter="app-table"></table>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="app-table-bar">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="reset-pwd">重置密码</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="open-im">开通im账号</a>
</script>

<!-- 员工信息编辑 -->
<script type="text/html" id="app-model">
    <div class="mb15 mt15">
        <form id="app-form" class="layui-form" lay-filter="app-form">
            <input type="hidden" name="id"/>

            <div class="layui-row mb15">
                <div class="layui-col-xs2 layui-col-xs-offset1 required layui-label-sm">
                    登录账号：
                </div>
                <div class="layui-col-xs8">
                    <input type="text" name="mobile" required placeholder="请输入手机号" autocomplete="off" class="layui-input layui-input-sm"
                    lay-verify="required|phoneUnique"/>
                </div>
            </div>

            <div class="layui-row mb15">
                <div class="layui-col-xs2 layui-col-xs-offset1 required layui-label-sm">
                    员工姓名：
                </div>
                <div class="layui-col-xs8">
                    <input type="text" name="name" required placeholder="请输入员工姓名" autocomplete="off" class="layui-input layui-input-sm"
                           />
                </div>
            </div>

            <div class="layui-row mb15">
                <div class="layui-col-xs2 layui-col-xs-offset1 required layui-label-sm">
                    员工编号:
                </div>
                <div class="layui-col-xs8">
                    <input id="no" name="no" placeholder="请输入员工编号" type="text" class="layui-input layui-input-sm"
                           lay-verify="required|noUnique" required/>
                </div>
            </div>

            <div class="layui-row mb15">
                <div class="layui-col-xs2 layui-col-xs-offset1 required layui-label-sm">
                    是否在职:
                </div>
                <div class="layui-col-xs8">
                    <input type="radio" name="inJob" value="1" title="是" checked>
                    <input type="radio" name="inJob" value="0" title="否">
                </div>
            </div>
            <div class="layui-row mb15">
                <div class="layui-col-xs2 layui-col-xs-offset1 layui-label-sm">
                    邮箱:
                </div>
                <div class="layui-col-xs8">
                    <input name="email" placeholder="请输入员工邮箱" type="text" class="layui-input layui-input-sm"
                           lay-verify="emailUnique"/>
                </div>
            </div>
            <div class="layui-row mb15">
                <div class="layui-col-xs2 layui-col-xs-offset1 layui-label-sm">
                    电话:
                </div>
                <div class="layui-col-xs8">
                    <input name="phone" placeholder="请输入员工电话称" type="text" class="layui-input layui-input-sm"
                    />
                </div>
            </div>
            <div class="layui-row mb15">
                <div class="layui-col-xs2 layui-col-xs-offset1 layui-label-sm">
                    备注信息:
                </div>
                <div class="layui-col-xs8">
                    <textarea name="description" placeholder="请输入员工备注信息" class="layui-textarea"></textarea>
                </div>
            </div>

            <div class="layui-form-item model-form-footer">
                <div class="layui-col-xs11">
                    <button class="layui-btn layui-btn-primary layui-btn-sm" ew-event="closeDialog" type="button">取消</button>
                    <button class="layui-btn layui-btn-normal layui-btn-sm" lay-submit>保存</button>
                </div>
            </div>
        </form>
    </div>
</script>

<script type="text/html" id="im-open-model">
    <div class="mb15 mt15">
        <form id="imopen-form" lay-filter="imopen-form" class="layui-form">
            <div class="layui-form-item">
                <div class="layui-col-xs2 layui-col-xs-offset1 required layui-label-sm">
                    im登录名：
                </div>
                <div class="layui-col-xs8">
                    <input id="im-username" name="username" placeholder="请输入im登录名" type="text" class="layui-input layui-input-sm"
                           lay-verify="required|imusernameUnique" required/>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-col-xs2 layui-col-xs-offset1 required layui-label-sm">
                    im密码：
                </div>
                <div class="layui-col-xs8">
                    <input id="impwd" name="password" placeholder="请输入im密码" type="password" class="layui-input layui-input-sm"
                           lay-verify="required|imPwdCheck" required/>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-col-xs2 layui-col-xs-offset1 required layui-label-sm">
                    确认密码：
                </div>
                <div class="layui-col-xs8">
                    <input id="impwd2" name="password2" placeholder="请再输入一次im密码" type="password" class="layui-input layui-input-sm"
                           lay-verify="required|imPwdCheck" required/>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-col-xs2 layui-col-xs-offset1 layui-label-sm">
                    im昵称：
                </div>
                <div class="layui-col-xs8">
                    <input name="nickname" placeholder="请输入im昵称" type="text" class="layui-input layui-input-sm"
                    />
                </div>
            </div>
            <div class="layui-form-item model-form-footer">
                <div class="layui-col-xs11">
                    <button class="layui-btn layui-btn-primary layui-btn-sm" ew-event="closeDialog" type="button">取消</button>
                    <button class="layui-btn layui-btn-normal layui-btn-sm" lay-submit>保存</button>
                </div>
            </div>

        </form>
    </div>

</script>

<script>
    layui.use(['config', 'form', 'admin', 'table', 'tools', 'layer'], function () {
        var form = layui.form;
        var table = layui.table;
        var tools = layui.tools;
        var layer = layui.layer;
        var config = layui.config;
        var admin = layui.admin;

        form.verify({

            /**
             * 员工手机号码唯一验证
             */
            phoneUnique: function (value, item) {
                var opType = tools.getTempData('op-type');
                if ('add' === opType) {
                    var result = '';
                    tools.request({
                        url: config.base_server + '/plm/sv/employee/check/phone/' + value,
                        method: 'get',
                        async: false,
                    }).done(function (res) {
                        if (0 != res.code) {
                            result = res.msg;
                        }
                    });
                    if (result.length > 0) {
                        return result;
                    }
                }
            },
            /**
             * 员工邮箱唯一验证
             */
            emailUnique: function (value, item) {
                var result = '';
                if (value.length > 0) {
                    tools.log('emailUnique=---------------');
                    tools.log(value);
                    tools.request({
                        url: config.base_server + '/plm/sv/employee/check/email/' + value,
                        method: 'get',
                        async: false,
                    }).done(function (res) {
                        if (0 != res.code) {
                            result = res.msg;
                        }
                    });
                }
                if (result.length > 0) {
                    return result;
                }
            },
            /**
             * 员工工号唯一验证
             */
            noUnique: function (value, item) {
                var opType = tools.getTempData('op-type');
                if ('add' === opType) {
                    tools.log('noUnique---------');
                    tools.log(value);
                    var result = '';
                    tools.request({
                        url: config.base_server + '/plm/sv/employee/check/no/' + value,
                        method: 'get',
                        async: false,
                    }).done(function (res) {
                        if (0 != res.code) {
                            result = res.msg;
                        }
                    });
                    return result;
                }
            },

            /**
             * im登录名唯一验证
             */
            imusernameUnique: function (value, item) {
                var result = '';
                tools.request({
                    url: config.base_server + '/im/api/users/' + value,
                    method: 'get',
                    async: false,
                }).done(function (res) {
                    if (404 == res.code) {
                        tools.log(res);
                    } else if (400 != res) {
                        tools.log(res);
                        result = '此登录名已存在';
                    }
                });
                if (result.length > 0) {
                    return result;
                }
            },

            /**
             * 开通im账号，两次密码一致验证
             */
            imPwdCheck: function (value, item) {
                var pwd = $('#impwd').val();
                var pwd2 = $('#impwd2').val();
                tools.log(pwd);
                tools.log(pwd2);
                if (pwd != pwd2) {
                    return '两次输入密码不一致';
                }
            }
        });

        methods = {
            doQuery() {
                var key = $('#app-edit-search').val();
                table.reload('app-table', {where: {keyWord: key}});
            },
            /**
             * 添加员工信息
             */
            doAdd() {
                tools.putTempData('op-type', 'add');
                methods.showEditModel('add');

            },
            /**
             * 重置员工登录密码
             */
            doResetPwd(obj) {
                layer.confirm('确定要重置密码吗？', function (i) {
                    tools.request({
                        url: config.base_server + '/plm/sv/employee/resetpwd/' + obj.data.id,
                        method: 'post'
                    }).done(function (res) {
                        if (0 == res.code) {
                            layer.msg('重置密码成功', {icon: 1});
                        } else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    });
                });
            },
            /**
             * 编辑员工信息
             */
            doEdit(obj) {
                tools.putTempData('op-type', 'edit');
                tools.putTempData('employee-info', obj.data);
                methods.showEditModel('edit');

            },
            /**
             * 开通im账号
             */
            doImOpen(obj) {
                methods.showImOpenModel();
            },

            /**
             * im 开通
             */
            showImOpenModel() {
                admin.popupCenter({
                    title: '开通员工im账号',
                    area: ['800px', '350px'],
                    content: $('#im-open-model').html(),
                    success: function (layero, index) {
                        methods.doImOpenFormSubmit();

                    }
                });
            },

            /**
             * im开通表单提交
             */
            doImOpenFormSubmit() {
                var employeeInfo = tools.getTempData('employee-info');
                form.on('submit(imopen-form)', function () {
                    var formData = tools.serializeArray('imopen-form');
                    formData.registerType = 2;
                    tools.log(formData);
                    tools.request({
                        url: config.base_server + '/plm/sv/employee/imopen/' + employeeInfo.id,
                        method: 'post',
                        dataType: "json",
                        contentType: "application/json",
                        data: formData
                    }).done(function (res) {
                        if (0 == res.code) {
                            layer.msg('开通im账号成功', {icon: 1});
                            table.reload('app-table', {});
                            layer.closeAll();
                        } else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    });
                    return false;
                });
            },

            /**
             * 基本信息编辑框
             */
            showEditModel(type) {
                var title = 'edit' === type ? '修改员工信息' : '添加员工信息';

                admin.popupCenter({
                    title: title,
                    area: ['700px', '510px'],
                    content: $('#app-model').html(),
                    finish: function () {

                    },
                    success: function (layero, index) {
                        form.render(null, 'app-form');
                        if ('edit' === type) {
                            layero.find('#mobile').attr('readonly', 'readonly');
                            layero.find('#no').attr('readonly', 'readonly');
                            layero.find('#password').attr('placeholder', '不修改密码则不需要填写');
                            layero.find('#password').removeAttr('lay-verify');
                            layero.find('#password').removeAttr('required');
                            layero.find('#password').parent().prev().removeClass('required');
                            layero.find('#password').next().hide();

                            layero.find('#password2').attr('placeholder', '不修改密码则不需要填写');
                            layero.find('#password2').removeAttr('lay-verify');
                            layero.find('#password2').removeAttr('required');
                            layero.find('#password2').parent().prev().removeClass('required');


                            var employeeInfo = tools.getTempData('employee-info');
                            tools.log(employeeInfo);
                            form.val('app-form', {
                                id: employeeInfo.id,
                                mobile: employeeInfo.mobile,
                                name: employeeInfo.name,
                                no: employeeInfo.no,
                                inJob: employeeInfo.inJob,
                                email: employeeInfo.email,
                                phone: employeeInfo.phone,
                                description: employeeInfo.description
                            });
                            form.render(null, 'app-form');
                        } else if ('add' == type) {
                            $('#app-form').find('input[name="id"]').val('');
                        }
                        methods.doAppFormSubmit();
                    }
                });
            },

            /**
             * 员工基本信息表单提交
             */
            doAppFormSubmit() {
                var opType = tools.getTempData('op-type');

                form.on('submit(app-form)', function () {
                    var formData = tools.serializeArray('app-form');
                    tools.log(formData);
                    if ('edit' == opType) {
                        tools.request({
                            url: config.base_server + '/plm/sv/employee/update',
                            method: 'post',
                            data: formData
                        }).done(function (res) {
                            if (0 == res.code) {
                                layer.closeAll();
                                table.reload('app-table', {});
                            } else {
                                layer.msg(res.msg, {icon: 5});
                            }
                        });
                    } else {
                        tools.request({
                            url: config.base_server + '/plm/sv/employee/add',
                            method: 'put',
                            data: formData
                        }).done(function (res) {
                            if (0 == res.code) {
                                layer.closeAll();
                                table.reload('app-table', {});
                            } else {
                                layer.msg(res.msg, {icon: 5});
                            }
                        });
                    }
                    return false;
                });
            },

            renderTable() {
                table.render({
                    elem: '#app-table',
                    url: config.base_server + '/plm/sv/employee/page',
                    method: 'GET',
                    page: true,
                    cols: [[
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', hide: true, title: 'id'},
                        {field: 'no', sort: false, title: '工号',width:120},
                        {field: 'username', sort: false, title: '登录账号',width:120},
                        {field: 'name', sort: false, title: '姓名',width:120},
                        {field: 'email', sort: false, title: '邮箱',width:220},
                        {field: 'mobile', sort: false, title: '手机',width:120},
                        {
                            field: 'inJob', sort: false, title: '是否在职',width:120,
                            templet: function (d) {
                                if (0 == d.inJob) {
                                    return '否';
                                } else {
                                    return '是';
                                }
                            }
                        },
                        {
                            field: 'imOpen', sort: false, title: 'im状态',width:90,
                            templet: function (d) {
                                if (0 == d.imOpen) {
                                    return '否';
                                } else {
                                    return '是';
                                }
                            }
                        },
                        {field: 'imUsername', sort: false, title: 'im用户名',width:120},
                        {align: 'id', width: 360, toolbar: '#app-table-bar', title: '操作'}
                    ]]
                });
            },
            toolbarEvent() {
                tools.log('toolbar ------------ Event');
                table.on('tool(app-table)', function (obj) {
                    tools.log('toolbarEvent');
                    tools.putTempData('employee-info', obj.data);
                    var data = obj.data;
                    var layEvent = obj.event;
                    if (layEvent === 'edit') {
                        tools.putTempData('op-type', 'edit');
                        methods.doEdit(obj);
                    } else if('reset-pwd' === layEvent){
                        methods.doResetPwd(obj);
                    }else if (layEvent === 'open-im') {
                        if (1 == data.imOpen) {
                            layer.msg('已开通im账号', {icon: 0});
                        } else {
                            methods.doImOpen(obj);
                        }
                    }
                });
            },
        };

        methods.renderTable();
        methods.toolbarEvent();

    });
</script>